package com.easy.interceptor;

import com.alibaba.fastjson.JSON;
import com.easy.util.LayData;
import com.easy.util.SYS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class SystemLoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(SystemLoginInterceptor.class);

    //在handler处理之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查请求是否有登陆状态
        String requestURI = request.getRequestURI();

        HttpSession session=request.getSession();
        Object obj=session.getAttribute(SYS.SYSTEM_LOGIN_ADMIN);

        logger.info("Request URI: {}, User logged in: {}", requestURI, obj!= null);
        //判断是否存在登陆数据
        if(obj!=null){
            return true;
        }else {
            // 返回 JSON 响应
            String requestwith = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestwith)) {
                //ajax
                LayData result = LayData.success(401, "您还没有登录,请登录");
                String json = JSON.toJSONString(result);
                System.out.println(json);
                response.setHeader("Content-Type", "application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
            } else {
                //分支判断 请求方式  访问页面   重定向
                //                ajax     json

                //重定向
                String path = request.getContextPath();
                String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
                response.sendRedirect(basePath + "sys/login");
                return false;
            }
            return false;
        }

    }
    //在handler处理之后立即执行
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//
//    }
    //一个请求结束spring的框架访问后 执行
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//
//    }
}
